package org.m2acsi.boundary;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.m2acsi.entities.RoleType;
import org.m2acsi.entities.User;
import org.m2acsi.entities.User_;

@Stateless
public class UserEJB extends BaseEJB<User> {

    @PersistenceContext(unitName = "taskManagerPU")
    EntityManager em;

    public UserEJB() {
        super(User.class);
    }

    @Override
    public void remove(User user) {
        user.setRoleName(RoleType.DISABLED);
        update(user);
    }

    @Override
    public EntityManager em() {
        return em;
    }

    @Override
    public List<User> findAll() {
        CriteriaBuilder cBuilder = em.getCriteriaBuilder();
        CriteriaQuery<User> cQuery = cBuilder.createQuery(entityClass);
        Root<User> u = cQuery.from(entityClass);
        cQuery.select(u);
        cQuery.where(cBuilder.notEqual(u.get(User_.roleName), RoleType.DISABLED));
        return em.createQuery(cQuery).getResultList();
    }

    public List<User> findAllUsers(String filtre) {
        CriteriaBuilder cBuilder = em.getCriteriaBuilder();
        CriteriaQuery<User> cQuery = cBuilder.createQuery(entityClass);
        Root<User> u = cQuery.from(entityClass);
        cQuery.select(u);
        if (filtre != null) {
            cQuery.where(cBuilder.like(u.get(User_.firstname), filtre + "%"));
        }
        return em.createQuery(cQuery).getResultList();
    }

    public List<User> findUsers(RoleType roleType) {
        CriteriaBuilder cBuilder = em.getCriteriaBuilder();
        CriteriaQuery<User> cQuery = cBuilder.createQuery(entityClass);
        Root<User> u = cQuery.from(entityClass);
        cQuery.select(u);
        cQuery.where(cBuilder.equal(u.get(User_.roleName), roleType));
        return em.createQuery(cQuery).getResultList();
    }

    public User findUser(String email) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<User> criteria = cb.createQuery(entityClass);
        Root<User> root = criteria.from(entityClass);
        criteria.select(root);
        criteria.where(cb.equal(root.get(User_.email), email));
        try {
            return em.createQuery(criteria).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }
}
